package authority

import (
	"errors"
	"cgs-server/server"
	"cgs-server/server/base"
	"cgs-server/server/model"
	"go.mongodb.org/mongo-driver/bson"
)

type AuthorityRepository interface {
	base.Repository
	// 根据名称查找权限
	FindByMenuName(name string) (*model.MenuAuthority, error)
	// 查询所有 menu 权限
	FindAllMenuAuth(mdl *model.DataUserModel) ([]*model.MenuAuthority, error)
}

func NewAuthorityRepository() AuthorityRepository {
	return &authorityRepository{base.RepositoryStruct{
		CollectionName: server.AuthorityCollectionName,
	}}
}

type authorityRepository struct {
	base.RepositoryStruct
}

func (a *authorityRepository) FindByMenuName(name string) (*model.MenuAuthority, error) {
	if err := a.CheckDB(); err != nil {
		return nil, err
	}
	filter := bson.M{
		"name": name,
	}
	result := &model.MenuAuthority{}
	find, err := a.Mongo.FindOne(a.CollectionName, filter, result)
	if err != nil {
		return nil, err
	}
	if find {
		return result, nil
	} else {
		return nil, errors.New("menu auth not found")
	}
}

// 添加权限
func (a *authorityRepository) Insert(mdl *model.DataUserModel) error {
	if _, ok := mdl.Data.(*model.MenuAuthority); ok {
		if err := a.CheckDB(); err != nil {
			return err
		}
		_, err := a.Mongo.InsertOne(a.CollectionName, mdl.Data)
		return err
	} else {
		return errors.New("MenuAuth type error.")
	}
}

// 获取所有权限
func (a *authorityRepository) FindAllMenuAuth(mdl *model.DataUserModel) ([]*model.MenuAuthority, error) {
	if err := a.CheckDB(); err != nil {
		return nil, err
	}
	filter := bson.M{
		"type": "MENU",
	}
	results := []*model.MenuAuthority{}
	err := a.Mongo.FindMany(a.CollectionName, filter, &results)
	if err != nil {
		return nil, err
	}
	return results, nil
}

// 修改权限
func (a *authorityRepository) Update(mdl *model.DataUserModel) error {
	if auth, ok := mdl.Data.(*model.MenuAuthority); ok {
		filter := bson.M{
			"name": auth.Name,
		}
		update := bson.M{
			"$set": bson.M{
				"menuPath": auth.MenuPath,
				"visible": auth.Visible,
			},
		}
		_, err := a.Mongo.UpdateOne(a.CollectionName, filter, update)
		return err
	} else {
		return errors.New("Auth type error")
	}
}

// 删除权限
func (a *authorityRepository) Delete(mdl *model.DataUserModel) error {
	if auth, ok := mdl.Data.(*model.MenuAuthority); ok {
		filter := bson.M{
			"name": auth.Name,
		}
		_, err := a.Mongo.DeleteOne(a.CollectionName, filter)
		return err
	} else {
		return errors.New("Auth type error")
	}
}
